package gui.panel_new.evaluation.professor;

import enums.*;
import gui.other.SylogismPremisaViewerDialog;
import gui.panel_new.evaluation.exeptions.ExerciseNotBuiltException;
import gui.panel_new.evaluation.exeptions.PunctuationZeroException;
import j_util.Utiles;
import misc.BundlesProvider;
import model.Polisilogismo;
import model.Premisa;
import model.eval.TestExcercise;
import model.eval.TestExerciseOposicion;
import model.mchoice.OposicionMCItem;
import model.mchoice.OposicionMCItemSet;

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ResourceBundle;
/*

    This file is part of Logica-Logike.

    Logica-Logike is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation version 3 of the License.

    Logica-Logike is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Logica-Logike.  If not, see <http://www.gnu.org/licenses/>.

 */
/**
 * Extebsion de CreateExcercisePanel, destinada a la creacion de ejercicios de cuadro de oposicion;
 *
 * @author Jose Martin Rozanec;
 */
public class CreateOposicionEvaluationPanel extends CreateExercisePanel {
    private JLabel answersLabel;
    private JLabel firstAnswerLabel;
    private JLabel secondAnswerLabel;
    private JLabel thirdAnswerLabel;
    private JLabel fourthAnswerLabel;
    private JTextField firstAnswerTextField;
    private JTextField secondAnswerTextField;
    private JTextField thirdAnswerTextField;
    private JTextField fourthAnswerTextField;
    private JCheckBox true1;
    private JCheckBox true2;
    private JCheckBox true3;
    private JCheckBox true4;
    private JCheckBox false1;
    private JCheckBox false2;
    private JCheckBox false3;
    private JCheckBox false4;
    private JCheckBox indeterminated1;
    private JCheckBox indeterminated2;
    private JCheckBox indeterminated3;
    private JCheckBox indeterminated4;
    private JLabel addsPoints;
    private JLabel substractPoints;
    private JTextField addsPointsField;
    private JTextField substractPointsField;
    private JButton addQuestionButton;
    private JButton resetQuestionButton;
    private JTextArea fullQuestionaireTextArea;
    private JTextField questionsQuantityTextField;
    private JCheckBox fixedPunctuationCheckBox;
    private JTextField fixedPunctuationField;
    private JCheckBox oneAnswerPerQuestionCheckBox;
    private JTextField substractProportionalityTextField;
    private JButton createExerciseButton;
    private JTextField premisaField;
    private JCheckBox verdadera;
    private JCheckBox falsa;
    private JCheckBox indeterminada;
    private JComboBox combo1;
    private ResourceBundle textBundle;
    private JPanel questionsPanel;

    private OposicionMCItemSet oposicionMCItemSet;
    private Premisa premisa;
    private int answers;

    private boolean resetMode;

    /**
     * Constructor;
     *
     * @param saveButton;
     * @param openButton;
     * @param fileChooser;
     */
    public CreateOposicionEvaluationPanel(JButton saveButton, JButton openButton, JFileChooser fileChooser) {
        this.saveButton = saveButton;
        this.openButton = openButton;
        this.fileChooser = fileChooser;
        fileFilter = FileFilterEnum.XML;
        testPanelEnum = TestPanelEnum.OPOSICION;
        oposicionMCItemSet = new OposicionMCItemSet();
        initComponents();
        initGUI();
        disableAnswers();
    }

    /**
     * Inicializa los elementos del panel;
     */
    private void initComponents() {
        resetMode = false;
        textBundle = BundlesProvider.getBundle(URLEnum.TEXT_BUNDLE);
        answersLabel = new JLabel(textBundle.getString(TextBundleEnum.ANSWERS.toString()));
        firstAnswerLabel = new JLabel("A- ");
        secondAnswerLabel = new JLabel("E- ");
        thirdAnswerLabel = new JLabel("I- ");
        fourthAnswerLabel = new JLabel("O- ");
        firstAnswerTextField = new JTextField(25);
        secondAnswerTextField = new JTextField(25);
        thirdAnswerTextField = new JTextField(25);
        fourthAnswerTextField = new JTextField(25);
        true1 = new JCheckBox();
        true2 = new JCheckBox();
        true3 = new JCheckBox();
        true4 = new JCheckBox();
        false1 = new JCheckBox();
        false2 = new JCheckBox();
        false3 = new JCheckBox();
        false4 = new JCheckBox();
        indeterminated1 = new JCheckBox();
        indeterminated2 = new JCheckBox();
        indeterminated3 = new JCheckBox();
        indeterminated4 = new JCheckBox();

        premisaField = new JTextField(30);
        verdadera = new JCheckBox("V");
        verdadera.setSelected(true);
        verdadera.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                manageVFLogic();
            }
        });
        falsa = new JCheckBox("F");
        falsa.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                manageVFLogic();
            }
        });
        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(verdadera);
        buttonGroup.add(falsa);
        buttonGroup.add(indeterminada);
        combo1 = new JComboBox();

        addsPoints = new JLabel(textBundle.getString(TextBundleEnum.SUMA.toString()));
        substractPoints = new JLabel(textBundle.getString(TextBundleEnum.RESTA.toString()));
        addsPointsField = new JTextField(5);
        addsPointsField.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                if (!addsPointsField.getText().equals("")) {
                    double substract = Double.parseDouble(substractProportionalityTextField.getText());
                    substractPointsField.setText("" + (int) (substract * Integer.parseInt(addsPointsField.getText())));
                }
            }
        });
        substractPointsField = new JTextField(5);
        substractPointsField.setEditable(false);
        addQuestionButton = new JButton(textBundle.getString(TextBundleEnum.AGREGAR_PREGUNTA.toString()));
        resetQuestionButton = new JButton(textBundle.getString(TextBundleEnum.RESETEAR_PREGUNTA.toString()));
        fullQuestionaireTextArea = new JTextArea(10, 48);// rows;columns
        questionsQuantityTextField = new JTextField(14);//32 //todo
        fixedPunctuationCheckBox = new JCheckBox(
                textBundle.getString(TextBundleEnum.FIXED_PUNCTUATION.toString()));
        fixedPunctuationCheckBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                fixedPunctuationField.setEditable(fixedPunctuationCheckBox.isSelected());
            }
        });
        fixedPunctuationField = new JTextField(11);
        oneAnswerPerQuestionCheckBox = new JCheckBox(textBundle.getString(
                TextBundleEnum.ONE_ANSWER_PER_QUESTION.toString()));
        substractProportionalityTextField = new JTextField(4);//22
        substractProportionalityTextField.setToolTipText(
                textBundle.getString(
                        TextBundleEnum.SUBSTRACT_PER_QUESTION_PROPORTIONALITY_TOOLTIP.toString()));
        createExerciseButton = new JButton(textBundle.getString(
                TextBundleEnum.CREATE_EXCERCISE.toString()));
        questionsPanel = new JPanel();
        addButtonsActionListeners();
        reset();
    }

    /**
     * Dispone los elementos visuales del panel;
     */
    private void initGUI() {
        setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        add(createMCItemSetOptionsPanel(), gridBagConstraints);
        gridBagConstraints.gridy = 1;
        add(createQuestionCreationPanel(), gridBagConstraints);
        enableQuestionsPanel(false);
    }

    /**
     * Crea un JPanel que contiene opciones de MCItemSet;
     *
     * @return JPanel;
     */
    private JPanel createMCItemSetOptionsPanel() {
        int x = 0;
        int y = 0;
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY),
                textBundle.getString(TextBundleEnum.OPOSICION_TEST_OPTIONS.toString())));
        panel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        JPanel auxPanel1 = new JPanel();
        auxPanel1.setLayout(new GridBagLayout());
        gridBagConstraints.gridwidth = 6;//5
        auxPanel1.add(new JLabel(textBundle.getString(
                TextBundleEnum.QUESTIONS_QUANTITY.toString()) + ": "), gridBagConstraints);
        x = 6;//5
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 9;//10
        auxPanel1.add(questionsQuantityTextField, gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 30;
        panel.add(auxPanel1, gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 22;//11
        JPanel auxPanel2 = new JPanel();
        auxPanel2.add(fixedPunctuationCheckBox);
        auxPanel2.add(fixedPunctuationField);
        panel.add(auxPanel2, gridBagConstraints);//fixedPunctuationCheckBox
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 17;//8
        JPanel auxPanel3 = new JPanel(new GridBagLayout());
        auxPanel3.add(new JLabel(textBundle.getString(
                TextBundleEnum.SUBSTRACT_PER_QUESTION_PROPORTIONALITY.toString()) + ": "), gridBagConstraints);
        x = 17;//8
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 13;//7
        auxPanel3.add(substractProportionalityTextField, gridBagConstraints);
        gridBagConstraints.gridwidth = 30;
        gridBagConstraints.gridx = 0;
        panel.add(auxPanel3, gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        panel.add(createExerciseButton, gridBagConstraints);
        //cantidad de preguntas, puntuacion proporcional, si existe una respuesta estricta por pregunta
        return panel;
        //ver posibilidad de revisar las preguntas...
    }

    /**
     * Crea un panel en el que se han de ingresar la premisa modelo y mostrar las premisas restantes de acuerdo
     * al valor de verdad o falsedad asignado a la primera premisa;
     *
     * @return;
     */
    private JPanel createQuestionCreationPanel() {
        int x = 0;
        int y = 0;
        questionsPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        fullQuestionaireTextArea.setEditable(false);
        questionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                textBundle.getString(TextBundleEnum.CREAR_PREGUNTA.toString()) + " 1 " +
                        textBundle.getString(TextBundleEnum.DE.toString()) + " " + questionsQuantityTextField.getText()));
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        gridBagConstraints.gridwidth = 4;
        questionsPanel.add(createQuestionPanel(), gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 2;
        questionsPanel.add(answersLabel, gridBagConstraints);
        x = 2;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridwidth = 1;
        questionsPanel.add(createCheckLinePanel(), gridBagConstraints);
        gridBagConstraints.gridwidth = 1;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(createScoringPanel(), gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridheight = 1;
        questionsPanel.add(firstAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(firstAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(createCheckLinePanel1(), gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(secondAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(secondAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(createCheckLinePanel2(), gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(thirdAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(thirdAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(createCheckLinePanel3(), gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        questionsPanel.add(fourthAnswerLabel, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(fourthAnswerTextField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        questionsPanel.add(createCheckLinePanel4(), gridBagConstraints);
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        x = 0;
        gridBagConstraints.gridx = x;
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridwidth = 4;
        questionsPanel.add(createButtonsPanel(), gridBagConstraints);
        gridBagConstraints.gridy = ++y;
        gridBagConstraints.gridheight = 6;
        questionsPanel.add(createFullQuestionairePanel(), gridBagConstraints);
        clearAllFields();
        return questionsPanel;
    }

    /**
     * Crea un panel que contiene tres checkBoxes, uno que refiere a valor de verdad, otro que refiere a valor de
     * falsedad y el tercero que refiere a valor desconocido [la premisa puede ser verdadera o falsa];
     *
     * @return JPanel;
     */
    private JPanel createCheckLinePanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        int x = 0;
        int y = 0;
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 15, 5, 10);
        panel.add(new JLabel("V"), gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(new JLabel("F"), gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(new JLabel("V/F"), gridBagConstraints);
        return panel;
    }

    /**
     * Metodo auxiliar, crea un JPanel que dispone JLabels y JTextFields uno al lado de otro;
     *
     * @return JPanel;
     */
    private JPanel createQuestionPanel() {
        int x = 0;
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 2, 5, 2);
        gridBagConstraints.gridx = x;
        panel.add(new JLabel(textBundle.getString(TextBundleEnum.PREMISA.toString())), gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(premisaField, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(new JLabel(Utiles.createImageIcon(URLEnum.getReference(URLEnum.SPACE_OP))), gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(verdadera, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(falsa, gridBagConstraints);
        combo1.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"-", "A", "E", "I", "O"}));
        combo1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                premisa = new Premisa(premisaField.getText());
                switch (combo1.getSelectedIndex()) {
                    case 1://A
                        premisa.convert(ExtensionEnum.A);
                        break;
                    case 2://E
                        premisa.convert(ExtensionEnum.E);
                        break;
                    case 3://I
                        premisa.convert(ExtensionEnum.I);
                        break;
                    case 4://O
                        premisa.convert(ExtensionEnum.O);
                        break;
                    case 0://no hace nada
                        break;
                }
                premisaField.setText(premisa.toString());
            }
        });
        gridBagConstraints.gridx = ++x;
        panel.add(new JLabel(Utiles.createImageIcon(URLEnum.getReference(URLEnum.SPACE_OP))), gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(combo1, gridBagConstraints);

        premisaField.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent e) {
                if (Premisa.isComplete(premisaField.getText())) {
                    premisa = new Premisa(premisaField.getText());
                    premisaField.setForeground(new Color(0, 0, 0));
                    Premisa auxPremisa = new Premisa(premisaField.getText());
                    auxPremisa.convert(ExtensionEnum.A);
                    firstAnswerTextField.setText(auxPremisa.toString());
                    auxPremisa.convert(ExtensionEnum.E);
                    secondAnswerTextField.setText(auxPremisa.toString());
                    auxPremisa.convert(ExtensionEnum.I);
                    thirdAnswerTextField.setText(auxPremisa.toString());
                    auxPremisa.convert(ExtensionEnum.O);
                    fourthAnswerTextField.setText(auxPremisa.toString());
                    manageVFLogic();
                } else {
                    premisaField.setForeground(new Color(255, 0, 0));
                }
            }
        });
        return panel;
    }

    /**
     * Metodo auxiliar para agrupar JCheckBoxes;
     *
     * @return JPanel;
     */
    //todo considerar la union de los sucesivos metodos createCheckLinePanel; ya que en principio no es logico crear metodos identicos:)
    private JPanel createCheckLinePanel1() {
        JPanel panel = new JPanel(new GridBagLayout());
        int x = 0;
        int y = 0;
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        panel.add(true1, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(false1, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(indeterminated1, gridBagConstraints);
        return panel;
    }

    private JPanel createCheckLinePanel2() {
        JPanel panel = new JPanel(new GridBagLayout());
        int x = 0;
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        panel.add(true2, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(false2, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(indeterminated2, gridBagConstraints);
        return panel;
    }

    private JPanel createCheckLinePanel3() {
        JPanel panel = new JPanel(new GridBagLayout());
        int x = 0;
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        panel.add(true3, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(false3, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(indeterminated3, gridBagConstraints);
        return panel;
    }

    private JPanel createCheckLinePanel4() {
        JPanel panel = new JPanel(new GridBagLayout());
        int x = 0;
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        panel.add(true4, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(false4, gridBagConstraints);
        gridBagConstraints.gridx = ++x;
        panel.add(indeterminated4, gridBagConstraints);
        return panel;
    }

    /**
     * Crea un JPanel a partir del cual se establece el puntaje propio del ejercicio;
     *
     * @return JPanel;
     */
    private JPanel createScoringPanel() {
        JPanel scoringPanel = new JPanel();
        scoringPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY),
                textBundle.getString(TextBundleEnum.PUNTAJE.toString())));
        scoringPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(5, 5, 5, 5);
        scoringPanel.add(addsPoints, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        scoringPanel.add(addsPointsField, gridBagConstraints);
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridx = 0;
        scoringPanel.add(substractPoints, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        scoringPanel.add(substractPointsField, gridBagConstraints);
        return scoringPanel;
    }

    /**
     * Crea un panel con botones que refieren a opciones de reset y de agregar una nueva pregunta;
     *
     * @return JPanel;
     */
    private JPanel createButtonsPanel() {
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.insets = new Insets(0, 25, 0, 25);
        gridBagConstraints.gridx = 0;
        buttonsPanel.add(addQuestionButton, gridBagConstraints);
        gridBagConstraints.gridx = 1;
        buttonsPanel.add(resetQuestionButton, gridBagConstraints);
        return buttonsPanel;
    }

    /**
     * Crea el JScrollPane en el cual se muestra la totalidad del cuestionario creado hasta el momento;
     *
     * @return
     */
    private JScrollPane createFullQuestionairePanel() {
        JScrollPane scrollPane = new JScrollPane(fullQuestionaireTextArea);
        scrollPane.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),
                textBundle.getString(TextBundleEnum.CUESTIONARIO_CREADO.toString())));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        return scrollPane;
    }

    /**
     * Agrega los ActionListeners a los botones de CreateOposicionEvaluationPanel;
     */
    private void addButtonsActionListeners() {
        addQuestionButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (performQuestionCheckings()) {
                    OposicionMCItem item = new OposicionMCItem();
                    item.setQuestion(premisaField.getText());
                    item.setSolutions(firstAnswerTextField.getText(), 1);
                    item.setSolutionStatus(getStatus(true1, false1), 1);
                    item.setSolutions(secondAnswerTextField.getText(), 2);
                    item.setSolutionStatus(getStatus(true2, false2), 2);
                    item.setSolutions(thirdAnswerTextField.getText(), 3);
                    item.setSolutionStatus(getStatus(true3, false3), 3);
                    item.setSolutions(fourthAnswerTextField.getText(), 4);
                    item.setSolutionStatus(getStatus(true4, false4), 4);

                    item.setCorrectPunctuation(Integer.parseInt(addsPointsField.getText()));
                    item.setIncorrectPunctuation(Integer.parseInt(substractPointsField.getText()));
                    item.setQuestionTrue(verdadera.isSelected());
                    oposicionMCItemSet.addMCItem(item);
                    manageQuestionPanelBorder();
                    clearAllFields();
                    fullQuestionaireTextArea.setText(oposicionMCItemSet.toString());
                    premisaField.requestFocus();
                }

            }
        });

        resetQuestionButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clearAllFields();
            }
        });

        createExerciseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (resetMode) {
                    reset();

                } else {
                    if (performMCParametersCheckings()) {
                        enableQuestionsPanel(true);
                        enableMCOptionsPanel(false);
                        manageButtonGroup();
                        managePointsFields();
                        clearAllFields();
                        manageQuestionPanelBorder();
                        fullQuestionaireTextArea.setText("");
                    }
                }
            }
        });
    }

    /**
     * A partir de dos checkBoxes [uno que refiere a un valor de verdad y otro que refiere a un valor
     * de falsedad de una misma premisa] se determina el valor de OposicionValuesEnum que significan;
     *
     * @param trueCheckBox;
     * @param falseCheckBox;
     * @return OposicionValuesEnum;
     */
    private OposicionValuesEnum getStatus(JCheckBox trueCheckBox, JCheckBox falseCheckBox) {
        if (trueCheckBox.isSelected()) {
            return OposicionValuesEnum.TRUE;
        }
        if (falseCheckBox.isSelected()) {
            return OposicionValuesEnum.FALSE;
        }
        return OposicionValuesEnum.INDETERMINATED;
    }

    /**
     * Crea ButtonGroups, agrupando los checkBoxes de cada premisa;
     */
    private void manageButtonGroup() {
        ButtonGroup buttonGroup1 = new ButtonGroup();
        buttonGroup1.add(true1);
        buttonGroup1.add(false1);
        buttonGroup1.add(indeterminated1);

        ButtonGroup buttonGroup2 = new ButtonGroup();
        buttonGroup2.add(true2);
        buttonGroup2.add(false2);
        buttonGroup2.add(indeterminated2);

        ButtonGroup buttonGroup3 = new ButtonGroup();
        buttonGroup3.add(true3);
        buttonGroup3.add(false3);
        buttonGroup3.add(indeterminated3);

        ButtonGroup buttonGroup4 = new ButtonGroup();
        buttonGroup4.add(true4);
        buttonGroup4.add(false4);
        buttonGroup4.add(indeterminated4);
    }

    /**
     * Deduce los valores que deben obtener las demas premisas a partir del valor de la premisa modelo;
     */
    private void manageVFLogic() {
        if (premisa != null) {
            checkCheckBoxes(false);
            if (verdadera.isSelected()) {
                vfLogic_v(premisa.getPartsExtension());
            } else {
                vfLogic_f(premisa.getPartsExtension());
            }
        }
    }

    /**
     * Auxiliar de manageVFLogic(), analiza si la premisa modelo es verdadera;
     *
     * @param extension - extension de la premisa modelo;
     */
    private void vfLogic_v(ExtensionEnum extension) {
        switch (extension) {
            case A:
                true1.setSelected(true);
                false2.setSelected(true);
                true3.setSelected(true);
                false4.setSelected(true);
                break;
            case E:
                false1.setSelected(true);
                true2.setSelected(true);
                false3.setSelected(true);
                true4.setSelected(true);
                break;
            case I:
                indeterminated1.setSelected(true);
                false2.setSelected(true);
                true3.setSelected(true);
                indeterminated4.setSelected(true);
                break;
            case O:
                false1.setSelected(true);
                indeterminated2.setSelected(true);
                indeterminated3.setSelected(true);
                true4.setSelected(true);
                break;
        }
    }

    /**
     * Auxiliar de manageVFLogic(), analiza si la premisa modelo es falsa;
     *
     * @param extension - extension de la premisa modelo;
     */
    private void vfLogic_f(ExtensionEnum extension) {
        switch (extension) {
            case A:
                vfLogic_v(ExtensionEnum.O);
                break;
            case E:
                vfLogic_v(ExtensionEnum.I);
                break;
            case I:
                vfLogic_v(ExtensionEnum.E);
                break;
            case O:
                vfLogic_v(ExtensionEnum.A);
                break;
        }

    }

    /**
     * Permite marcar/desmarcar todos los checkBoxes;
     *
     * @param check
     */
    private void checkCheckBoxes(boolean check) {
        true1.setSelected(check);
        true2.setSelected(check);
        true3.setSelected(check);
        true4.setSelected(check);
        false1.setSelected(check);
        false2.setSelected(check);
        false3.setSelected(check);
        false4.setSelected(check);
        indeterminated1.setSelected(check);
        indeterminated2.setSelected(check);
        indeterminated3.setSelected(check);
        indeterminated4.setSelected(check);
    }

    /**
     * Maneja la habilidatcion de los JTextFields referentes a puntaje del ejercicio;
     */
    private void managePointsFields() {
        if (fixedPunctuationCheckBox.isSelected()) {
            addsPointsField.setEditable(false);
            substractPointsField.setEditable(false);
        }
    }

    /**
     * Limpia todos los valores presentes en los JTextFields del panel;
     */
    private void clearAllFields() {
        premisaField.setText("");
        firstAnswerTextField.setText("");
        secondAnswerTextField.setText("");
        thirdAnswerTextField.setText("");
        fourthAnswerTextField.setText("");
        addsPointsField.setText("0");
        substractPointsField.setText("0");
        if (oneAnswerPerQuestionCheckBox.isSelected()) {
            true1.setSelected(true);
        }
        if (fixedPunctuationCheckBox.isSelected()) {
            addsPointsField.setText(fixedPunctuationField.getText());
        }
    }

    /**
     * Realiza los chequeos necesarios antes de determinar que la pregunta pueda ser agregada al set de preguntas;
     *
     * @return boolean - si paso o no todos los chequeos;
     */
    private boolean performQuestionCheckings() {
        if (!Premisa.isComplete(premisaField.getText())) {
            JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                    textBundle.getString(TextBundleEnum.WARNING_COMPLETAR_DATOS_MCHOICE.toString()),
                    "", JOptionPane.WARNING_MESSAGE);
            return false;
        } else {
            /*no deberia darse el caso,ya que verifica cada item por separado*/
            if (Integer.parseInt(addsPointsField.getText()) == 0) {
                JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                        textBundle.getString(TextBundleEnum.WARNING_SUMA_CERO.toString()),
                        "", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }
        return true;
    }

    /**
     * Realiza los chequeos referentes a parametros de la pregunta antes de determinar que la pregunta pueda ser
     * agregada al set de preguntas;
     *
     * @return boolean - si paso o no todos los chequeos;
     */
    private boolean performMCParametersCheckings() {
        substractProportionalityTextField.setText(substractProportionalityTextField.getText().replace(",", "."));
        if (questionsQuantityTextField.getText().equals("") ||
                substractProportionalityTextField.getText().equals("")) {
            JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                    textBundle.getString(TextBundleEnum.WARNING_COMPLETAR_DATOS.toString()),
                    "", JOptionPane.WARNING_MESSAGE);
        } else {
            try {
                if (Integer.parseInt(questionsQuantityTextField.getText()) < 1) {
                    JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                            textBundle.getString(TextBundleEnum.WARNING_CANTIDAD_PREGUNTAS_POSITIVO_MAYOR_UNO.toString()) + "!",
                            "", JOptionPane.WARNING_MESSAGE);
                    return false;
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                        textBundle.getString(TextBundleEnum.WARNING_CANTIDAD_PREGUNTAS_ENTERO.toString()) + "!",
                        "", JOptionPane.WARNING_MESSAGE);
                return false;
            }
            if (Double.parseDouble(substractProportionalityTextField.getText()) > 1 ||
                    Double.parseDouble(substractProportionalityTextField.getText()) < 0) {
                JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                        textBundle.getString(TextBundleEnum.WARNING_PROPORCIONALIDAD_ENTRE_CERO_UNO.toString()) + "!",
                        "", JOptionPane.WARNING_MESSAGE);
                return false;
            }
            if (fixedPunctuationCheckBox.isSelected()) {
                if (fixedPunctuationField.getText().equals("")) {
                    JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                            textBundle.getString(TextBundleEnum.WARNING_COMPLETAR_DATOS.toString()),
                            "", JOptionPane.WARNING_MESSAGE);
                } else {
                    try {
                        if (Integer.parseInt(fixedPunctuationField.getText()) < 1) {
                            JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                                    textBundle.getString(TextBundleEnum.WARNING_SUMAR_POSITIVO.toString()) + "!",
                                    "", JOptionPane.WARNING_MESSAGE);
                            return false;
                        }
                    } catch (NumberFormatException e) {
                        JOptionPane.showMessageDialog(CreateOposicionEvaluationPanel.this,
                                textBundle.getString(TextBundleEnum.WARNING_SUMAR_ENTERO.toString()) + "!",
                                "", JOptionPane.WARNING_MESSAGE);
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * Habilita o no el panel en el cual se mustran las premisas;
     *
     * @param enable;
     */
    private void enableQuestionsPanel(boolean enable) {
        fullQuestionaireTextArea.setEnabled(enable);
        addQuestionButton.setEnabled(enable);
        resetQuestionButton.setEnabled(enable);
        substractPointsField.setEnabled(enable);
        addsPointsField.setEnabled(enable);
        premisaField.setEnabled(enable);
        verdadera.setEnabled(enable);
        falsa.setEnabled(enable);
        combo1.setEnabled(enable);
    }

    /**
     * Desabilita los checkBoxes;
     */
    private void disableAnswers() {
        true1.setEnabled(false);
        true2.setEnabled(false);
        true3.setEnabled(false);
        true4.setEnabled(false);
        false1.setEnabled(false);
        false2.setEnabled(false);
        false3.setEnabled(false);
        false4.setEnabled(false);
        indeterminated1.setEnabled(false);
        indeterminated2.setEnabled(false);
        indeterminated3.setEnabled(false);
        indeterminated4.setEnabled(false);
        firstAnswerTextField.setEditable(false);
        secondAnswerTextField.setEditable(false);
        thirdAnswerTextField.setEditable(false);
        fourthAnswerTextField.setEditable(false);
    }

    /**
     * Permite habilitar o no el panel de opciones del conjunto de ejercios de oposicion;
     *
     * @param enable;
     */
    private void enableMCOptionsPanel(boolean enable) {
        questionsQuantityTextField.setEnabled(enable);
        substractProportionalityTextField.setEnabled(enable);
        fixedPunctuationCheckBox.setEnabled(enable);
        fixedPunctuationField.setEnabled(enable);
        oneAnswerPerQuestionCheckBox.setEnabled(enable);
        resetMode = !enable;
        if (resetMode) {
            createExerciseButton.setText(textBundle.getString(TextBundleEnum.RESETEAR_EJERCICIO.toString()));
        } else {
            createExerciseButton.setText(textBundle.getString(TextBundleEnum.CREATE_EXCERCISE.toString()));
        }
    }

    /**
     * Maneja los valores presentes en el borde del panel de preguntas;
     */
    private void manageQuestionPanelBorder() {
        if (oposicionMCItemSet.getMCItems().size() < Integer.parseInt(questionsQuantityTextField.getText())) {
            questionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                    textBundle.getString(TextBundleEnum.CREAR_PREGUNTA.toString()) +
                            " " + (oposicionMCItemSet.getMCItems().size() + 1) + " " +
                            textBundle.getString(TextBundleEnum.DE.toString()) + " " +
                            questionsQuantityTextField.getText()));
        } else {
            enableMCOptionsPanel(true);
            enableQuestionsPanel(false);
        }
    }

    public TestExcercise getExercise() throws ExerciseNotBuiltException, PunctuationZeroException {
        if (oposicionMCItemSet.getMCItems().size() < Integer.parseInt(questionsQuantityTextField.getText())
                || addsPointsField.getText().equals("") || substractPointsField.getText().equals("")) {
            throw new ExerciseNotBuiltException();
        }
        if (oposicionMCItemSet.getPuntuation() == 0) {
            throw new PunctuationZeroException();
        }
        TestExcercise testExercise = new TestExerciseOposicion();
        testExercise.setExerciseData(oposicionMCItemSet);
        testExercise.setStudentsSolution(oposicionMCItemSet.getDefaultSet());
        return testExercise;
    }

    public void setExercise(TestExcercise testExcercise) {
        this.oposicionMCItemSet = (OposicionMCItemSet) testExcercise.getExcerciseData();
        fullQuestionaireTextArea.setText(oposicionMCItemSet.toString());
        OposicionMCItem item = oposicionMCItemSet.current();
        premisaField.setText(item.getQuestion());
        verdadera.setSelected(item.isQuestionTrue());
        falsa.setSelected(!item.isQuestionTrue());
        manageVFLogic();
    }

    /**
     * Permite obtener el puntaje maximo que se puede lograr con la resolucion correcta del ejercicio;
     *
     * @return score;
     */
    public int getCorrectScore() {
        return oposicionMCItemSet.getPuntuation();
    }

    /**
     * Resetea el panel de creacion de ejercicio;
     */
    public void reset() {
        questionsQuantityTextField.setText("10");
        fixedPunctuationField.setText("10");
        substractProportionalityTextField.setText("0.5");
        fixedPunctuationCheckBox.setSelected(false);
        oneAnswerPerQuestionCheckBox.setSelected(true);
        clearAllFields();
        enableMCOptionsPanel(true);
        enableQuestionsPanel(false);
        oposicionMCItemSet = new OposicionMCItemSet();
        questionsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
                textBundle.getString(TextBundleEnum.CREAR_PREGUNTA.toString()) +
                        " " + (oposicionMCItemSet.getMCItems().size() + 1) + " " +
                        textBundle.getString(TextBundleEnum.DE.toString()) + " " +
                        questionsQuantityTextField.getText()));
        fixedPunctuationField.setEditable(false);
        fullQuestionaireTextArea.setText("");
    }

    protected void setSaveActionListener() {
        class SavePremisaAction extends AbstractAction {
            public SavePremisaAction() {
                super("", Utiles.createImageIcon(URLEnum.getReference(URLEnum.SAVE_AS)));
            }

            public void actionPerformed(ActionEvent e) {
//                if (!premisa.isComplete(premisaField.getText())) {
//                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
//                            textBundle.getString(TextBundleEnum.WARNING_DONT_SAVE_EMPTY_PREMISA.toString()),
//                            "", JOptionPane.WARNING_MESSAGE);
//                }
                if (oposicionMCItemSet.getTotalQuestions() < Integer.parseInt(questionsQuantityTextField.getText())) {
                    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                            textBundle.getString(TextBundleEnum.WARNING_EXCERCISE_NOT_COMPLETE.toString()),
                            "", JOptionPane.WARNING_MESSAGE);
                } else {
                    String path = "";
                    int state = fileChooser.showSaveDialog(JOptionPane.getRootFrame());
                    if (state == JFileChooser.APPROVE_OPTION) {
                        path = fileChooser.getSelectedFile().getPath();
                        Utiles.saveTextFileAlertingOverwrite(path, ".xml", premisa.toXML());
                    }
                }
            }
        }
        saveButton.setAction(new SavePremisaAction());
    }

    protected void setSaveButtonEnabled() {
        saveButton.setEnabled(true);
    }

    protected void setOpenActionListener() {
        class OpenSylogismAction extends AbstractAction {
            public OpenSylogismAction() {
                super("", Utiles.createImageIcon(URLEnum.getReference(URLEnum.OPEN)));
            }

            public void actionPerformed(ActionEvent e) {
                String path = "";
                int state = fileChooser.showOpenDialog(JOptionPane.getRootFrame());
                if (state == JFileChooser.APPROVE_OPTION) {
                    path = fileChooser.getSelectedFile().getPath();
                    try {
                        RandomAccessFile randomAccessFile = new RandomAccessFile(path, "r");
                        String xml = randomAccessFile.readUTF();

                        if (xml.startsWith(Premisa.openTag())) {
                            setPremisa(Premisa.parseXML(xml));
                        } else {
                            if (xml.startsWith(Polisilogismo.openTag())) {
                                SylogismPremisaViewerDialog sylogismPremisaViewerDialog = new SylogismPremisaViewerDialog(
                                        Polisilogismo.parseXML(xml).getIterator());
                                Utiles.centerDialog(sylogismPremisaViewerDialog);
                                sylogismPremisaViewerDialog.setSize(new Dimension(400, 200));
                                sylogismPremisaViewerDialog.setResizable(false);
                                sylogismPremisaViewerDialog.setModal(true);
                                sylogismPremisaViewerDialog.setVisible(true);
                                if (sylogismPremisaViewerDialog.accepted()) {
                                    setPremisa(sylogismPremisaViewerDialog.getPremisa());
                                }
                            } else {
                                JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                        textBundle.getString(TextBundleEnum.WARNING_ARCHIVO_INCORRECTO_SILOGISMO.toString()));
                            }
                        }
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        openButton.setAction(new OpenSylogismAction());
    }

    protected void setOpenButtonEnabled() {
        openButton.setEnabled(true);
    }

    protected void setFocusOnComponent() {
        //remains unimplemented...
    }

    /**
     * Setea la premisa modelo;
     *
     * @param premisa;
     */
    private void setPremisa(Premisa premisa) {
        premisaField.setText(premisa.toString());
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setContentPane(new CreateOposicionEvaluationPanel(new JButton(), new JButton(), new JFileChooser()));
        frame.setSize(new Dimension(500, 500));
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}